import React, {useState, useEffect} from 'react';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { Button, Form, Input, Upload, message, Modal } from 'antd';
import { Scrollbars } from 'react-custom-scrollbars';
import { formatTime } from '../../util/util';

import style from './FeatureEdit.module.scss';

const filterKeys = ['uid', 'updateTime', 'image'];

const {IMAGE_URL} = window.CONFIG;

const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);

        reader.onload = () => resolve(reader.result);

        reader.onerror = (error) => reject(error);
});

const FeatureEdit = (props) => {
    const {editData={}, fieldNames, setEditShow, updateFeature, saveLoading} = props;

    const [formData, setFormData] = useState({});
    const [loading, setLoading] = useState(false);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');       // 预览图片地址
    const [previewTitle, setPreviewTitle] = useState('');       // 预览图片标题
    const [prevImageUrl, setPrevImageUrl] = useState('');       // 原始图片路径
    const [fileList, setFileList] = useState([]);               // 上传图片列表

    const [form] = Form.useForm();

    useEffect(() => {
        if(Object.keys(editData).length === 0) return;
        // 筛选表单编辑字段
        let filterData = {};
        
        Object.keys(editData).forEach(key => {
            if(!filterKeys.includes(key)){
                const value = String(editData[key]) || '';
                if(value.includes('T') && value.includes('00+')){
                    filterData[key] = formatTime(value);
                }else{
                    filterData[key] = value;
                }
            }
        });

        if(editData['image']){
            filterImages(editData['image']);
        }

        // 初始表单填充
        form.setFieldsValue({
            ...filterData
        });

        setFormData(filterData);
    },[editData]);

    // 图片信息提取
    const filterImages = (image) => {
        // "\\da45f2a9c83d030d\\1663384883366\\,微信图片_20220903114238.jpg"
        const imageArr = image.split(',');
        let prevUrl = ''    
        let imageList = [];
        imageArr.forEach((item,index) => {
            if(index === 0){
                prevUrl = item;
            }else{
                const list = {
                    status: 'done',
                    uid: index,
                    title: item,
                    url: `${IMAGE_URL}${prevUrl}${item}`
                };
                imageList.push(list);
            }
        });
        setPrevImageUrl(prevUrl);
        setFileList(imageList);
    };

    // 上传前图片校验
    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

        if (!isJpgOrPng) {
            message.error('您只能上传 JPG 或 PNG 文件!');
        }

        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isLt2M) {
            message.error('图片大小不能超过 2MB!');
        }

        return isJpgOrPng && isLt2M;
    };

    // 图片预览
    const handlePreview = async (file) => {
        if(!file.originFileObj) return;
        
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
    
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    };

    // 图片上传
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
      
        if (info.file.status === 'done') {
            const {file: {response}} = info;
            const {code} = response;
            if(code === 200){
                setFileList(info.fileList);
            }
            setLoading(false);
        }
    };

    // 图片移除
    const handleRemove = (file) => {
        const index = fileList.findIndex((item) => {
            return item.uid === file.uid;
        });
        let copyFileList = JSON.parse(JSON.stringify(fileList));
        if(index > -1){
            copyFileList.splice(index, 1);
        }
        setFileList(copyFileList);
    };

    // 提交
    const onFinish = (values) => {
        const {images='', ...resetValues} = values;
        const {uid} = editData;
        let items = JSON.parse(JSON.stringify(resetValues));
        const {tempArr, imageTitles} = getImages(images);

        if(tempArr.length > 0){
            items['temp'] = tempArr.join(',');
        }

        if(imageTitles.length > 0){
            items['image'] = [prevImageUrl,...imageTitles].join(',');
        }else{
            if(prevImageUrl){
                items['image'] = prevImageUrl;
            }
        }

        if(items['key']){
            delete items['key'];
        }

        const params = {
            operationContent: {
                items,
                itemsPrev: {},
                operation: 'update',
                uid
            }
        };
        
        updateFeature(params);
        setEditShow(false);
    };

    // 解析图片
    const getImages = (images) => {
        let tempArr = [];
        let imageTitles = [];
        if(!images) {
            return{
                tempArr,imageTitles
            }
        } 
        
        const {fileList} = images;

        fileList.forEach(item => {
            const {response} = item;
            if(response){
                const {code, data} = response;
                if(code === 200) {
                    const {temp = ''} = data;
                    temp && tempArr.push(temp);
                }
            }else{
                const {title} = item;
                title && imageTitles.push(title);
            }
        });
        return {tempArr, imageTitles};
    };

    // 取消
    const onCancel = () => {
        setEditShow(false);
    };

    const formItems = Object.keys(formData).filter(item => item !== 'key').map((key) => {
        return (
            <Form.Item label={fieldNames[key] ? fieldNames[key] : key} name={key} key={key}>
                <Input />
            </Form.Item>
        )
    });

    const buttonItemLayout ={
        wrapperCol: {
            span: 14,
            offset: 8
        }
    };

    return (
        <div className={style.featureEdit}>
            <Scrollbars autoHeight autoHeightMin={0} autoHeightMax={`calc(100vh - 250px)`}>
                <Form
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 16 }}
                    layout="horizontal"
                    form={form}
                    onFinish={onFinish}
                >
                    
                    {formItems}
                    <Form.Item label="图片" valuePropName="images" name="images">
                        <Upload 
                            action="/webapi/2.0/image/upload" 
                            listType="picture-card" 
                            fileList={fileList} 
                            beforeUpload={beforeUpload} 
                            onPreview={handlePreview}
                            onRemove={handleRemove}
                            onChange={handleChange}>
                                {
                                    fileList.length > 5 ? null : 
                                        <div>
                                            {loading ? <LoadingOutlined /> : <PlusOutlined />}
                                            <div style={{ marginTop: 8 }}>上传</div>
                                        </div>
                            }
                                
                        </Upload>
                    </Form.Item>
                    <Form.Item label="" {...buttonItemLayout}>
                        <Button type="primary" htmlType="submit" className={style.commit} loading={saveLoading}>提交</Button>
                        <Button type="primary" onClick={onCancel}>取消</Button>
                    </Form.Item>
                </Form>
            </Scrollbars>
            
            <Modal visible={previewOpen} title={previewTitle} footer={null} onCancel={() => setPreviewOpen(false)}>
                <img
                    alt="example"
                    style={{
                        width: '100%',
                    }}
                    src={previewImage}
                />
            </Modal>
        </div>
    )
};

export default FeatureEdit;